package com.wk.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 在IE 里面, 即使安装了Chrome Frame, 进行Ajax 请求还是会受到IE 的cache 的影响的.
 * 所以在这里, 将从Chrome Frame 过来的对restful 的请求都禁用掉cache.
 * @author chenxiaozhong
 */
@WebFilter(urlPatterns = "/restful/*")
public class ChromeFrameCacheFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(final ServletRequest req, final ServletResponse resp,
			final FilterChain chain) throws IOException, ServletException {
		final HttpServletRequest request = (HttpServletRequest) req;
		final HttpServletResponse response = (HttpServletResponse) resp;

		final String userAgent = request.getHeader("user-agent");
		final String uri = request.getRequestURI();
		if (userAgent != null && !userAgent.equals("") && userAgent.indexOf("chromeframe") > 0 && !isImageUri(uri)) {
			// 在IE 里面, 即使安装了Chrome Frame, 进行Ajax 请求还是会受到IE 的cache 的影响的.
			// 所以在这里, 将对restful 的请求都禁用掉cache.
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Expires", "0");
		}

		chain.doFilter(req, resp);
	}

	private boolean isImageUri(final String uri) {
		return uri.indexOf("userimage") >= 0;
	}

	@Override
	public void init(final FilterConfig arg0) throws ServletException {
	}

}
